package com.itheima.mianshi.bubble;

public class BubbleSort {
    public static void main(String[] args) {
        int[] a = {1, 3, 2, 5, 4, 6, 7, 8, 9, 10};
        bubble(a);

        System.out.println();
        int[] b = {1, 3, 2, 5, 4, 6, 7, 8, 9, 10};
        bubble2(b);

        System.out.println();
        int[] c = {1, 3, 2, 5, 4, 6, 7, 8, 9, 10};
        bubble3(c);

    }

    /**
     * 冒泡排序 未优化版本
     *
     * @param a
     */
    public static void bubble(int[] a) {
        for (int i = 0; i < a.length - 1; i++) {
            for (int j = 0; j < a.length - 1 - i; j++) {
                if (a[j] > a[j + 1]) {
                    int temp = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = temp;
                }
            }
            System.out.println("第" + (i + 1) + "轮排序后的数组" + java.util.Arrays.toString(a));
        }
    }

    /**
     * 冒泡排序 优化版本
     *
     * @param a
     */
    public static void bubble2(int[] a) {
        for (int i = 0; i < a.length - 1; i++) {
            boolean flag = true;
            for (int j = 0; j < a.length - 1 - i; j++) {
                if (a[j] > a[j + 1]) {
                    int temp = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = temp;
                    flag = false;
                }
            }
            if (flag) {
                break;
            }
            System.out.println("第" + (i + 1) + "轮排序后的数组" + java.util.Arrays.toString(a));
        }
    }

    /**
     * 冒泡排序 优化版本2
     *
     * @param a
     */
    public static void bubble3(int[] a) {
        int k = a.length - 1;
        while (true) {
            int pos = 0; // 表示最后一次交换的位置
            for (int i = 0; i < k; i++) {
                if (a[i] > a[i + 1]) {
                    int temp = a[i];
                    a[i] = a[i + 1];
                    a[i + 1] = temp;
                    pos = i;
                }
            }
            k = pos;
            if (k == 0) {
                break;
            }
            System.out.println("第" + (a.length - k) + "轮排序后的数组" + java.util.Arrays.toString(a));
        }
    }
}
